/*
 * QStringAdapter.cpp  0.4.0 / Nov 14, 2010
 *
 * Copyright (c) 2010 - 2011, cute4j.com and contributors.
 *
 * This software is licensed under the LGPL version 2.1 license.
 * A copy of this license is included in the file LICENSE-LGPL.txt.
 */
#include "QStringAdapter.h"

#include "JNIWrapper.h"

// QStringAdapter :: Public Constructor. ---------------------------------------

/*!
 * \brief Constructs new QStringAdapter object.
 *
 * \param env the JNIEnv pointer
 * \param str the Java string object
 *
 * \exception OutOfMemoryError java error
 */
QStringAdapter::QStringAdapter(JNIEnv *env, jstring str)
  : QString()
{
  Q_ASSERT(env);
  if (str) {
    jsize size = env->GetStringLength(str);
    if (size > 0) {
      const jchar *unicode = env->GetStringCritical(str, 0);
      if (unicode) {  // checks for OutOfMemoryError
        setUnicode(reinterpret_cast<const QChar *>(unicode), size);
        env->ReleaseStringCritical(str, unicode);
      }
    } else {
      operator=(""); // TODO: clear
    }
  }
}

// QStringAdapter :: Public Member Functions. ----------------------------------

/*!
 * \brief Creates new Java string object using specified QString.
 *
 * \param env the JNIEnv pointer
 *
 * \return Java string object
 *
 * \exception OutOfMemoryError java error
 */
jstring QStringAdapter::toJString(JNIEnv *env)
{
  return JNIWrapper::newString(env,
                               reinterpret_cast<const jchar *>(constData()),
                               length());
}

// QStringAdapter :: Public Static Member Function. ----------------------------

/*!
 * \brief Creates new Java string using specified QString.
 *
 * \param env the JNIEnv pointer
 * \param str the QString reference
 *
 * \return Java string
 *
 * \exception OutOfMemoryError java error
 */
jstring QStringAdapter::toJString(JNIEnv *env, const QString &str)
{
  return JNIWrapper::newString(env,
                               reinterpret_cast<const jchar *>(str.constData()),
                               str.length());
}
